package tech.jabari.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 字符编码过滤器（对请求和响应对象进行编码过滤）
 * @author Jabari Lu
 * @title: CharacterFilter
 * @data 2020/7/31 15:41
 */
@WebFilter("/*")
public class CharacterFilter implements Filter {


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 过滤器：既能处理Servlet请求，也能放行处理css，js请求
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse)response;

        String path = req.getServletPath();
//        System.out.println("-------path:"+path); // /css/user/userRegister.css
        if (!(path.endsWith(".css") || path.endsWith(".js") || path.indexOf("index.jsp") != -1)) {
//            System.out.println("CharacterFilter.doFilter().....");
            //设置请求和响应的字符编码
            req.setCharacterEncoding("UTF-8");
            resp.setCharacterEncoding("UTF-8");
            resp.setHeader("Content-type", "text/html;charset=UTF-8");
        }
        // 放行(执行真正的请求URL) 如：/loginServlet
        chain.doFilter(request,response);
    }

}
